import sys
import subprocess
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox


class PortProxyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Port Proxy Setup")
        self.setGeometry(100, 100, 300, 250)

        # 创建布局
        self.layout = QVBoxLayout()

        # 监听端口输入
        self.listenport_label = QLabel("本机端口:")
        self.listenport_input = QLineEdit()
        self.listenport_input.setPlaceholderText('举例：7070')
        self.layout.addWidget(self.listenport_label)
        self.layout.addWidget(self.listenport_input)

        # 连接端口输入
        self.connectport_label = QLabel("子系统端口:")
        self.connectport_input = QLineEdit()
        self.connectport_input.setPlaceholderText('举例：8080')
        self.layout.addWidget(self.connectport_label)
        self.layout.addWidget(self.connectport_input)

        # 连接地址输入
        self.connectaddress_label = QLabel("子系统IP:")
        self.connectaddress_input = QLineEdit()
        self.layout.addWidget(self.connectaddress_label)
        self.layout.addWidget(self.connectaddress_input)

        # 获取子系统IP按钮
        self.get_ip_button = QPushButton("获取 WSL IP")
        self.get_ip_button.clicked.connect(self.get_wsl_ip)
        self.layout.addWidget(self.get_ip_button)

        # 按钮
        self.button = QPushButton("设置端口代理")
        self.button.clicked.connect(self.set_port_proxy)
        self.layout.addWidget(self.button)

        self.setLayout(self.layout)

    def get_wsl_ip(self):
        try:
            # 使用 wsl 命令获取 IP 地址
            result = subprocess.run(['wsl', 'hostname', '-I'], check=True, capture_output=True, text=True)
            ip_address = result.stdout.strip().split()[0]  # 获取第一个IP地址
            self.connectaddress_input.setText(ip_address)
            print(f"WSL IP Address: {ip_address}")
        except subprocess.CalledProcessError as e:
            error_message = e.stderr.strip() or "无法获取WSL IP地址"
            print(f"Error getting WSL IP address: {error_message}")
            self.show_err_message(f"获取WSL IP地址失败: {error_message}", self)

    def set_port_proxy(self):
        listenport = self.listenport_input.text().strip()
        connectport = self.connectport_input.text().strip()
        connectaddress = self.connectaddress_input.text().strip()

        if not all([listenport, connectport, connectaddress]):
            self.show_err_message("所有字段都必须填写", self)
            return

        # 调用 netsh 命令
        command = f'netsh interface portproxy add v4tov4 listenport={listenport} listenaddress=0.0.0.0 connectport={connectport} connectaddress={connectaddress}'
        try:
            # 执行命令并捕获输出
            result = subprocess.run(command, check=True, shell=True, capture_output=True, text=True)
            print("Port proxy set successfully.")
            self.show_info_message("端口代理设置成功", self)
        except subprocess.CalledProcessError as e:
            error_message = e.stderr.strip() or "未知错误"
            print(f"Error setting port proxy: {error_message}")
            self.show_err_message(f"设置端口代理失败: {error_message}", self)

    def show_info_message(self, message, parent):
        QMessageBox.information(parent, "信息", message)

    def show_err_message(self, message, parent):
        QMessageBox.critical(parent, "错误", message)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = PortProxyApp()
    window.show()
    sys.exit(app.exec_())
